import webSocketHelper from "../utils/socketHelper";
import WebSocket_User from "../template/user";

import { msg, msgType } from "../template/message";
import { IncomingMessage } from "http";
import { BaseRepository, tableType } from "../utils/insert_";
import Router from "koa-router";
import querystring from "querystring";
import ws_websocket from "ws"; // 直接导入构造函数
import m_users_chat_list from "./model/m_users_chat_list";
import User from "./model/m_user";


const userRouter = new Router({ prefix: "/connection" });
const users_chat_db = new BaseRepository<m_users_chat_list>("users_chat_list");
const users_db = new BaseRepository<User>("users");
const userList = new Map<string, WebSocket_User>();

function on_connection(socket: ws_websocket, response: IncomingMessage) {
  console.log(`新的客户端连接: ${response.url}`);
  const query = response.url!.split("?")[1];
  const params = querystring.parse(query);

  const id = params.id as string;
  const name = params.name as string;
  const avatarId = params.avatar as string;


  //参数验证
  let toMsg = new msg("you", "", null, msgType.system);
  if (!id || !name || !avatarId) {
    if (!id) {
      toMsg.content = "id不能为空";
    } else if (!name) {
      toMsg.content = "name不能为空";
    } else if (!avatarId) {
      toMsg.content = "avatar不能为空";
    }
    socket.send(JSON.stringify(toMsg));
    socket.close();
    return;
  } else if (userList.has(id)) {
    toMsg.content = "用户已存在";
    socket.send(JSON.stringify(toMsg));
    socket.close();
    return;
  }

  const newuser = new WebSocket_User(name, id, socket, `/avatar/${avatarId}.jpg`);
  const sendUsr=new WebSocket_User(name, id, null, avatarId);

  delete sendUsr.socket;

  socket.send(
    JSON.stringify(
      new msg(
        "you",
        { msg: "连接成功", id },
        sendUsr,
        msgType.system
      )
    )
  );

users_db.create({
  u_name:'',
  u_pwd:'',
  u_avatar_url:'',
  u_create_time:''
});


  userList.set(id, newuser);

  socket.on("message",(req)=>{on_message(req,socket)});

  socket.on("close", () => {
    on_close(socket);
  });
}


function on_message(req: ws_websocket.RawData,socket: ws_websocket) {
  
    try {
      const message = JSON.parse(req.toString()) as msg;
      if (
        typeof message.user !== "number" ||
        !message.content ||
        !message.to_id
      ) {
        socket.send(
          JSON.stringify(new msg("you", "消息格式不正确", null, msgType.system))
        );
        return;
      }

      const userId = message.user.toString();
      const sender = userList.get(userId);
      if (!sender) return;

      const { avatar, userName } = sender;
      const whos_msg = { avatar, userId, userName, message };
      if (
        message.msgType !== msgType.publish &&
        message.msgType !== msgType.private
      ) {
        socket.send(
          JSON.stringify(
            new msg(
              "you",
              "消息类型错误,只有publish和private类型",
              null,
              msgType.system
            )
          )
        );
      }

      if (message.msgType === msgType.publish) {
        userList.forEach((user) => user.socket.send(JSON.stringify(whos_msg)));
      } else if (message.msgType === msgType.private) {
        const recipient = userList.get(message.to_id);
        if (recipient) {
          recipient.socket.send(JSON.stringify(whos_msg));
        }
      }


    } catch (error) {
      console.error("消息解析错误:", error);
      socket.send(
        JSON.stringify(new msg("you", "消息处理出错", null, msgType.system))
      );
    }
  
}

function on_close(socket: ws_websocket) {
  for (const [id, user] of userList.entries()) {
    if (user.socket === socket) {
      userList.delete(id);
      console.log(`用户 ${id} 已断开连接`);
      break;
    }
  }
}

function on_error(error: Error) {
  console.error("WebSocket 服务器出错:", error);
}



function init() {
  try {
    if (!webSocketHelper.server) {
      throw new Error("HTTP server is not initialized in webSocketHelper");
    }

    // 创建 WebSocket 服务器
    webSocketHelper.wws = new ws_websocket.WebSocketServer({
      server: webSocketHelper.server,
      path: "/connection/ws",
    });

    webSocketHelper.wws.on("error", on_error);

    webSocketHelper.wws.on("connection", on_connection);
  } catch (err) {
    console.error("WebSocket 服务器初始化失败:", err);
  }

  // 定义路由
  userRouter.get("/", async (ctx) => {
    ctx.body = "获取所有用户";
  });
}

export function init_connection() {
  init();
}
export default userRouter;
